<template>
  <scroll-view
    enable-passive
    enhanced
    :show-scrollbar="false"
    scroll-y
    class="hb-w-full hb-h-full hb-px-4"
    refresher-enabled
    :refresher-triggered="refresherTriggered"
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onPullDownRefresh"
  >
    <view class="hb-pb-1">
      <template v-for="item in circleDataList" :key="item.id">
        <CommunityItem :item="item" @refresh="refreshFileList" />
      </template>
      <Loadmore v-if="circleDataList.length >= 10" :loading-type="loadingType" />
      <Empty v-if="circleDataList.length === 0" text="您暂未加入任何圈子" :padding-top="200" />
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
  import { CircleListResult } from '@/api/contact/types';
  import CommunityItem from './CommunityItem.vue';
  import { IQuery } from '@/api/types';
  import { circleList } from '@/api/contact';
  import { useUserStore } from '@/store/modules/user';
  import { propTypes } from '@/utils/propTypes';

  const { userInfo } = storeToRefs(useUserStore());
  const refresherTriggered = ref(false);

  const props = defineProps({
    keyWord: propTypes.string.def(''),
  });

  watch(
    [() => userInfo.value, () => props.keyWord],
    () => {
      refreshFileList();
    },
  );

  const query = reactive<IQuery>({
    current: 1,
    size: 10,
  });

  const circleDataList = ref<CircleListResult[]>([]);

  const loadingType = ref(0);

  // 获取文件列表
  async function getFileList() {
    const res = await circleList({ ...unref(query), keyWord: props.keyWord });
    loadingType.value = res.records.length === 0 ? 2 : 0;
    circleDataList.value = [...circleDataList.value, ...res.records];
  }

  /** 刷新数据 */
  async function refreshFileList() {
    circleDataList.value = [];
    query.current = 1;
    await getFileList();
  }

  refreshFileList();

  async function onPullDownRefresh() {
    refresherTriggered.value = true;
    await refreshFileList();
    refresherTriggered.value = false;
  }

  const onScrollToLower = async () => {
    console.log('onScrollToLower');
    if (loadingType.value === 1 || loadingType.value === 2) return;
    loadingType.value = 1;
    query.current++;
    await getFileList();
  };
</script>

<style scoped lang="scss"></style>
